/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Presenter;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Bush
 */
public class ClienteUDPPresenter implements Runnable{

    private String host;
    private String porta;
    private int envios;
    private static String mens = "";
    private int TOKEN_TIMESTAMP = 5;
    private int MAX_WAIT_TIME = 1000;
    private static String CRLF = "\r\n";

    public ClienteUDPPresenter() {

        host = "255.255.255.255";
        porta = "3000";
        envios = 1;
        mens = "";        

    }

    public void clientePingUdp(String host, String porta, int envios) throws UnknownHostException, SocketException, IOException {
        long sent_timestamp;
        InetAddress Host = InetAddress.getByName(host);
        int portNumber = Integer.parseInt(porta);
        DatagramSocket socket = new DatagramSocket();
        socket.setSoTimeout(MAX_WAIT_TIME);

        // Construir uma mensagem de ping para ser enviado para o servidor
        while (true) {
            String message = generatePing();
            DatagramPacket ping_request = new DatagramPacket(message.getBytes(), message.length(), Host, portNumber);

            //Envie a solicitação de ping
            sent_timestamp = System.currentTimeMillis();
            socket.send(ping_request);
            // Datagram pacote para segurar a resposta do servidor
            DatagramPacket ping_response = new DatagramPacket(new byte[message.length()], message.length());

            // Aguarde resposta de ping do servidor
            try {
                socket.receive(ping_response);
                PrintData(ping_response, sent_timestamp);
                Thread.sleep(10000);
            } catch (SocketTimeoutException e) {
                System.out.println("Nenhuma resposta foi recebida do servidor");
            } catch (Exception e) {
                // Outro erro desconhecido ocorreu Pode Ter Que não pode ser tratado
                e.printStackTrace();
                return;
            }
           
        }
    }

    public String generatePing() {
        //Para obter a data ea hora atual
        SimpleDateFormat sdfNow = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        String strNow = sdfNow.format(new Date(System.currentTimeMillis()));
        return "Estou Online " + System.currentTimeMillis() + " (" + strNow + ")";
    }

// Imprimir página ping fluxo de saída padrão
    public void PrintData(DatagramPacket request, long sent_timestamp) throws Exception {
        String response = new String(request.getData());
        String[] tokens = response.split("");

        // Criar timestamps são enviados e recebidos RTT
        //long sent_timestamp = new Long(tokens[TOKEN_TIMESTAMP]);
        long received_timestamp = System.currentTimeMillis();

        // RTT
        long rtt = received_timestamp - sent_timestamp;

        // Display results        
        System.out.println(response + "\r\nServidor : "+request.getAddress().getHostAddress()+" IP: "+ request.getAddress().getHostAddress()+ " " + "(RTT =" + rtt + "ms)" + CRLF);
    }

    @Override
    public void run() {
        try {   
            clientePingUdp(host, porta, envios);
        } catch (SocketException ex) {
            Logger.getLogger(ClienteUDPPresenter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ClienteUDPPresenter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
